import {
  CreateOneSessionDocument,
  CreateOneSessionInput,
  CreateOneSessionMutation,
  DeleteOneSessionDocument,
  DeleteOneSessionMutation,
  DescribeInstanceStatusDocument,
  DescribeInstanceStatusQuery,
  StartInstancesDocument,
  StartInstancesMutation,
  StopInstancesDocument,
  StopInstancesMutation
} from '@/generated/graphql'
import { Client } from '@urql/vue'
import { useIntervalFn } from '@vueuse/core'
import { join } from 'lodash-es'

class Ec2Services {
  private urqlClient: Client

  constructor(client: Client) {
    this.urqlClient = client
  }

  //获取关机时间 标签 duration (s)
  getSST(duration: number = 7200, terminate: number = 7200) {
    const t = new Date(Date.now() + duration * 1000)
    const h = t.getHours().toString()
    const m = t.getMinutes().toString()
    const stopTime = `${h.padStart(2, '0')}:${m.padStart(2, '0')}`

    const nowTimeHours = new Date().getHours()

    //join arr
    const dayArray = nowTimeHours > parseInt(h) ? ['stop', 'at', stopTime, 'nextday'] : ['stop', 'at', stopTime]
    return [
      {
        Key: 'Schedule',
        Value: join(dayArray, '-')
      },
      {
        Key: 'delete',
        Value: `${terminate}`
      }
    ]
  }

  async createSession(data: CreateOneSessionInput) {
    console.log(data)
    //后台管理调整后就不用这段代码了 
    // //转整数
    data.duration = Math.floor(data.duration);
    data.termiate = Math.floor(data.termiate);
    // //转数组
    // data.backends[0].data.SecurityGroupIds=[data.backends[0].data.SecurityGroupIds]
    // //公有云没有这个参数
    // delete data.backends[0].data.resourceDic

    const session = await this.urqlClient
      .mutation<CreateOneSessionMutation>(CreateOneSessionDocument, {
        data
      })
      .toPromise()

    const instanceIds = session.data?.createOneSession?.instances.map((x) => x.id)

    if (instanceIds) {
      await this.waitInstanceRunning(instanceIds)
    }
    return session
  }

  async describeInstanceStatus(instanceIds: string[]) {
    const res = await this.urqlClient
      .query<DescribeInstanceStatusQuery>(DescribeInstanceStatusDocument, {
        data: {
          InstanceIds: instanceIds
        }
      })
      .toPromise()

    const instanceStatus = res.data?.describeInstanceStatus
    if (!instanceStatus) return false

    for (let i = 0; i < instanceStatus.length; i++) {
      if (instanceStatus[i].currentStateName !== 'running') {
        return false
      }
    }

    return true
  }

  waitInstanceRunning(instanceIds: string[]) {
    const that = this
    return new Promise((resolve, reject) => {
      const { pause } = useIntervalFn(async () => {
        const res = await that.describeInstanceStatus(instanceIds)

        if (res) {
          pause()
          resolve(true)
        }
      })
    })
  }

  async deleteOneSession(sessionId: string) {
    await this.urqlClient
      .mutation<DeleteOneSessionMutation>(DeleteOneSessionDocument, {
        data: {
          id: sessionId,
          force: true
        }
      })
      .toPromise()
  }

  async startInstances(instanceIds: string[]) {
    await this.urqlClient
      .mutation<StartInstancesMutation>(StartInstancesDocument, {
        data: {
          InstanceIds: instanceIds
        }
      })
      .toPromise()
  }

  async stopInstances(instanceIds: string[]) {
    await this.urqlClient
      .mutation<StopInstancesMutation>(StopInstancesDocument, {
        data: {
          InstanceIds: instanceIds
        }
      })
      .toPromise()
  }
}

export { Ec2Services }
